package com.cdm.beans.cdm;

import java.util.List;

import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;

import net.sf.frails.JSFHelper;
import net.sf.frails.aop.annotations.InjectBean;
import net.sf.frails.bean.annotations.DefMbean;
import net.sf.frails.bean.annotations.PreRender;
import net.sf.frails.bean.annotations.Prop;

import com.cdm.domain.dao.ContentDAO;
import com.cdm.domain.dao.UserDAO;
import com.cdm.domain.service.Service;
import com.cdm.domain.service.ServiceImpl;
import com.cdm.persistence.Content;
import com.cdm.persistence.ContentState;
import com.cdm.persistence.ContentType;
import com.cdm.persistence.EntityManagerHelper;
import com.cdm.persistence.User;
import com.cdm.util.Constants;
import com.vivo.util.DTool;

@DefMbean
public class ContentTypeCreateBean {

	@Prop(readOnly = true)
	User loginUser;

	@Prop
	ContentType contentType;

	/*
	 * ReadOnly Select Lists
	 */
	@Prop(readOnly = true)
	List<User> cps;

	public SelectItemGroup getCpItems() {
		SelectItem[] items = new SelectItem[cps.size()];
		for (int i = 0; i < cps.size(); i++) {
			items[i] = new SelectItem(cps.get(i), cps.get(i).getUserName());
		}
		SelectItemGroup group = new SelectItemGroup();
		group.setSelectItems(items);
		return group;
	}

	@Prop(readOnly = true)
	List<ContentType> contentTypeList;

	public SelectItemGroup getContentTypeList() {
		int size = contentTypeList.size();
		SelectItem[] items = new SelectItem[size];
		for (int i = 0; i < size; i++) {
			ContentType type = contentTypeList.get(i);
			items[i] = new SelectItem(type, type.getName());
		}
		SelectItemGroup group = new SelectItemGroup();
		group.setSelectItems(items);
		return group;
	}

	@PreRender(failOutcome = "/content/contentTypeCreate")
	public boolean init() {
		Object object = JSFHelper.getFromApplication(Constants.LOGIN_USER_KEY);
		if (object instanceof User && object != null) {
			loginUser = (User) object;
		}
		return true;
	}

	public void create() {
		try {
			EntityManagerHelper.beginTransaction();
			EntityManagerHelper.getEntityManager().persist(contentType);
			EntityManagerHelper.commit();
			JSFHelper.addMessage("message_create_content_success");
		} catch (RuntimeException e) {
			JSFHelper.addMessage(e.getLocalizedMessage());
			try {
				EntityManagerHelper.rollback();
			} catch (RuntimeException ex) {
				ex.printStackTrace();
			}
		}
	}

	private ContentDAO contentDAO = new ContentDAO();

	private Service service = new ServiceImpl();

}
